//
//  AppDelegate.m
//  JackProduct
//
//  Created by Pei on 15/11/6.
//  Copyright © 2015年 Xiaobo Pei. All rights reserved.
//

#import "AppDelegate.h"
#import "YMIntroductionViewController.h"
#import "LoginViewController.h"
#import "IQKeyboardManager.h"
#import "JPUSHService.h"
#import "SureGongXuViewController.h"
#import "UserInfo.h"
#import "ToBeSureTaskViewController.h"
#import "ToBeChangeTaskDetailViewController.h"
#import "ToBeReviewedTaskDetailViewController.h"

@interface AppDelegate ()
{
    SureGongXuViewController *checkVC;
    ToBeSureTaskViewController *toBeSureTaskVC;
    ToBeChangeTaskDetailViewController *toBeChangeTaskVC;
    ToBeReviewedTaskDetailViewController *toBeReviewedVC;
}

@end

@implementation AppDelegate

@synthesize qualityControlVC, sceneControlVC, sceneVC, mineVC, rootVC;


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    manager.enable = YES;
    manager.shouldResignOnTouchOutside = YES;
    manager.shouldToolbarUsesTextFieldTintColor = YES;
    manager.enableAutoToolbar = YES;
    
    //注册
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidLoginNotification object:nil];
    
    //获取自定义消息
    //[defaultCenter addObserver:self selector:@selector(networkDidReceiveCustomeMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    
    //NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //Required
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //       categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories    nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];

    }
    
    //Required
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:@"693092e958fce35c504158c8"
                          channel:@"zjAppstore"
                 apsForProduction:YES
            advertisingIdentifier:@""];

    
    _loginVC = [[LoginViewController alloc] init];
    
    
    BOOL isFirstLaunch = [[NSUserDefaults standardUserDefaults] boolForKey:@"WelcomeWhenFirstStart"];
    if (!isFirstLaunch)
    {
        _introductVC = [[YMIntroductionViewController alloc] init];
        self.window.rootViewController = _introductVC;
    }
    else
    {
        [self loginView];
    }
    
    
    
    [self.window makeKeyAndVisible];
    return YES;
}


//通知方法
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    //调用接口
    NSLog(@"\n\n极光推送注册成功\n\n");
    
    //通知后台registrationID
    [[NSUserDefaults standardUserDefaults] setValue:[JPUSHService registrationID] forKey:@"JPUSHServiceRegistrationID"];
    
    //注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}

//- (void)networkDidReceiveCustomeMessage:(NSNotification*)notification{
//    NSDictionary * userInfo = [notification userInfo];
//    NSString *content = [userInfo valueForKey:@"content"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    NSString *customizeField1 = [extras valueForKey:@"123456"]; //自定义参数，key是自己定义的
//    NSLog(@"自定义message:%@",userInfo);
//    NSLog(@"推%@",content);
//    NSLog(@"推%@",extras);
//    NSLog(@"推%@",customizeField1);
//}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required -    DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    
    [JPUSHService handleRemoteNotification:userInfo];
    //数字清零
    //[JPUSHService resetBadge];
    
    
    checkVC = nil;
    toBeSureTaskVC = nil;
    toBeChangeTaskVC = nil;
    toBeReviewedVC = nil;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:Login_Status]) {
        NSString *contentStr = [userInfo objectForKey:@"content"];
        NSData *contentData = [contentStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *contentTempDic = [NSJSONSerialization JSONObjectWithData:contentData options:0 error:nil];
        
        if (contentTempDic != nil && contentTempDic.count > 0) {
            NSDictionary *contentDic = [contentTempDic objectForKey:@"extras"];
            NSString *SceneTypeStr = [contentDic valueForKey:@"SceneType"];
            NSString *OperateTypeStr = [contentDic valueForKey:@"OperateType"];
            if (SceneTypeStr != nil) {
                if ([SceneTypeStr intValue] == 0) { //0(现场检查)
                    if ([OperateTypeStr intValue] == 0) {//提交检查任务,客户端跳转待确认检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            //toBeSureTaskVC = [[ToBeSureTaskViewController alloc] initWithDicFromPush:@"27"];
                            toBeSureTaskVC = [[ToBeSureTaskViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeSureTaskVC];
                        }
                    }else if ([OperateTypeStr intValue] == 1){//确认检查任务,客户端跳转待整改检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            //toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:@"2" InspectionItemID:@"73"];
                            toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeChangeTaskVC];
                        }
                        
                    }else if ([OperateTypeStr intValue] == 2){//提交整改任务,客户端跳转待审核检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            toBeReviewedVC = [[ToBeReviewedTaskDetailViewController alloc] initWithDicFrom:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeReviewedVC];
                        }
                        
                    }else if ([OperateTypeStr intValue] == 3){//审核整改任务,通过
                        //只是通知
                    }else if ([OperateTypeStr intValue] == 4){//审核整改任务,拒绝,客户端跳转待待整改检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeChangeTaskVC];
                        }
                        
                    }
                }else{//1(质量监控)
                    if (OperateTypeStr != nil) {
                        if ([OperateTypeStr intValue] == 5) {//提交关键工序,跳转至关键工序确认列表
                            checkVC = [[SureGongXuViewController alloc] initFromPush];
                            checkVC.navTitle = @"关键工序确认";
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:checkVC];
                        }else if ([OperateTypeStr intValue] == 6){//确认关键工序
                            //只是通知
                        }
                    }
                }
            }
        }
    }else{
        [self loginView];
    }

    
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // IOS 7 Support Required
    
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    /*
     {
     "msg_content": "您有一个检查单等待确认,点击查看",
     "extras": {
     "SceneType": 0,
     "OperateValue": "{\"InspectionID\":18}",
     "OperateType": 0
     }
     }
     */
    
    checkVC = nil;
    toBeSureTaskVC = nil;
    toBeChangeTaskVC = nil;
    toBeReviewedVC = nil;
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:Login_Status]) {
        NSString *contentStr = [userInfo objectForKey:@"content"];
        NSData *contentData = [contentStr dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *contentTempDic = [NSJSONSerialization JSONObjectWithData:contentData options:0 error:nil];
        
        if (contentTempDic != nil && contentTempDic.count > 0) {
            NSDictionary *contentDic = [contentTempDic objectForKey:@"extras"];
            NSString *SceneTypeStr = [contentDic valueForKey:@"SceneType"];
            NSString *OperateTypeStr = [contentDic valueForKey:@"OperateType"];
            if (SceneTypeStr != nil) {
                if ([SceneTypeStr intValue] == 0) { //0(现场检查)
                    if ([OperateTypeStr intValue] == 0) {//提交检查任务,客户端跳转待确认检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            //toBeSureTaskVC = [[ToBeSureTaskViewController alloc] initWithDicFromPush:@"27"];
                            toBeSureTaskVC = [[ToBeSureTaskViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeSureTaskVC];
                        }
                    }else if ([OperateTypeStr intValue] == 1){//确认检查任务,客户端跳转待整改检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            //toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:@"2" InspectionItemID:@"73"];
                            toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeChangeTaskVC];
                        }
                        
                    }else if ([OperateTypeStr intValue] == 2){//提交整改任务,客户端跳转待审核检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            toBeReviewedVC = [[ToBeReviewedTaskDetailViewController alloc] initWithDicFrom:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeReviewedVC];
                        }
                        
                    }else if ([OperateTypeStr intValue] == 3){//审核整改任务,通过
                        //只是通知
                    }else if ([OperateTypeStr intValue] == 4){//审核整改任务,拒绝,客户端跳转待待整改检查任务查看详细页面,检查任务ID从OperateValue中获取
                        NSDictionary *valueDic = [contentDic objectForKey:@"OperateValue"];
                        if (valueDic != nil && valueDic.count > 0) {
                            toBeChangeTaskVC = [[ToBeChangeTaskDetailViewController alloc] initWithDicFromPush:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionID"] intValue]] InspectionItemID:[NSString stringWithFormat:@"%d", [[valueDic valueForKey:@"InspectionItemID"] intValue]]];
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:toBeChangeTaskVC];
                        }
                        
                    }
                }else{//1(质量监控)
                    if (OperateTypeStr != nil) {
                        if ([OperateTypeStr intValue] == 5) {//提交关键工序,跳转至关键工序确认列表
                            checkVC = [[SureGongXuViewController alloc] initFromPush];
                            checkVC.navTitle = @"关键工序确认";
                            self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:checkVC];
                        }else if ([OperateTypeStr intValue] == 6){//确认关键工序
                            //只是通知
                        }
                    }
                }
            }
        }
    }else{
        [self loginView];
    }
    
    
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    
}

#pragma mark ********************* 自定义方法 *****************
- (void)rootView{
    
    qualityControlVC = nil;
    sceneControlVC = nil;
    sceneVC = nil;
    mineVC = nil;
    
    rootVC = nil;
    
    if (qualityControlVC == nil)
    {
        qualityControlVC = [[QualityControlViewController alloc] init];
    }
    if (sceneControlVC == nil)
    {
        sceneControlVC = [[SceneControlViewController alloc] init];
    }
    if (sceneVC == nil)
    {
        sceneVC = [[MySceneViewController alloc] init];
    }
    if (mineVC == nil)
    {
        mineVC = [[MineViewController alloc] init];
    }
    
    NSDictionary *sceneDic = [NSDictionary dictionaryWithObjectsAndKeys:
                              [[UINavigationController alloc]initWithRootViewController:sceneVC],kViewController,@"08xianchangjiankong-hui-",kNormalImage,@"08xianchangjiankong-",kSelectedImage,nil];
    
    NSDictionary *qualityControlDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [[UINavigationController alloc]initWithRootViewController:qualityControlVC],kViewController,@"06xianchangjiancha-hui",kNormalImage,
                                       @"06xianchangjiancha",kSelectedImage,nil];
    NSDictionary *sceneControlDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [[UINavigationController alloc]initWithRootViewController:sceneControlVC],kViewController,@"07zhiliangjiankong-hui-",kNormalImage,
                                     @"07zhiliangjiankong-",kSelectedImage,nil];
    
    NSDictionary *mineDic = [NSDictionary dictionaryWithObjectsAndKeys:
                             [[UINavigationController alloc]initWithRootViewController:mineVC],kViewController,@"09gerenzhongxin-hui",kNormalImage,
                             @"09gerenzhongxin",kSelectedImage,nil];
    
    if (rootVC == nil)
    {
        rootVC = [[RootViewController alloc] init];
        rootVC.view.backgroundColor = kWhiteColor;
    }
    
    rootVC.titleArray = [NSArray arrayWithObjects:@"现场检查", @"质量监控", @"现场监控", @"个人中心",nil];
    rootVC.viewControllers = [NSArray arrayWithObjects:sceneDic,qualityControlDic,sceneControlDic,mineDic,nil];
    
    self.window.rootViewController = rootVC;
}

- (void)loginView{
    if ([[NSUserDefaults standardUserDefaults] boolForKey:Login_Status])
    {
        [self rootView];
    }
    else
    {
        self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:_loginVC];
    }
    
}


@end
